package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/*
 * check_inService业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */

@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


/*
     * 查询check_in
     * 
     * @param id check_in主键
     * @return check_in
      */

    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

/*
     * 查询check_in列表
     * 
     * @param checkIn check_in
     * @return check_in
 */

    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

/*
     * 新增check_in
     * 
     * @param checkIn check_in
     * @return 结果
 */

    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

/*
     * 修改check_in
     * 
     * @param checkIn check_in
     * @return 结果
 */

    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

/*
     * 批量删除check_in
     * 
     * @param ids 需要删除的check_in主键
     * @return 结果
 */

    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

/*
     * 删除check_in信息
     * 
     * @param id check_in主键
     * @return 结果
 */

    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    /**
     *查询
    * */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<Elder>();
        queryWrapper.eq(Elder::getId, checkIn.getElderId());
        Elder elder = elderMapper.selectOne(queryWrapper);
        //查询入住信息

        BeanUtils.copyProperties(checkIn, checkInDetailVo);
        //查询老人信息
        checkInDetailVo.setCheckInElderVo(selectElder(elder));
        //查询合同
        Long elderId = elder.getId();
        LambdaQueryWrapper<Contract> queryWrapperC = new LambdaQueryWrapper<Contract>();
        queryWrapperC.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(queryWrapperC);
        checkInDetailVo.setContract(contract);
        //查询入住配置
        CheckInConfigVo checkInConfigVo = getCheckInConfigById(checkIn);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        /*LambdaQueryWrapper<CheckInConfig> queryWrapperCIC = new LambdaQueryWrapper<CheckInConfig>();
        queryWrapperCIC.eq(CheckInConfig::getCheckInId,checkIn.getId());

        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapperCIC);
        BeanUtils.copyProperties(checkInConfig, checkInDetailVo.getCheckInConfigVo());*/
        //转换家属列表
       List<ElderFamilyVo> lsit = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
       checkInDetailVo.setElderFamilyVoList(lsit);
        //返回
        return checkInDetailVo;
    }

    private CheckInConfigVo getCheckInConfigById(CheckIn checkIn) {
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<CheckInConfig>();
        queryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setEndDate(checkInConfig.getFeeEndDate());
        return checkInConfigVo;
    }

    private CheckInElderVo selectElder(Elder elder) {
       CheckInElderVo checkInElderVo = new CheckInElderVo();
       BeanUtils.copyProperties(elder, checkInElderVo);
       Integer near  = Integer.valueOf(elder.getIdCardNo().toString().substring(6, 10));
       Integer now =Integer.valueOf( LocalDateTime.now().toString().substring(0, 4));
       checkInElderVo.setAge(now - near);
       return checkInElderVo;
    }







    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<Elder>();
        queryWrapper.eq(Elder::getIdCardNo,
                dto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder)){
            throw new RuntimeException("老人已入住");
        }
        //更新床位
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //跟新保存老人
        elder = insertOrUpdate(bed,dto.getCheckInElderDto());
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        // 新增签约办理
        insertContract(contractNo, elder, dto);
        // 新增入住信息
        CheckIn checkIn = insertCheckIno(elder,dto);
        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);
    }
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto dto) {
        // 新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }
    private CheckIn insertCheckIno(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        checkInMapper.insert(checkIn);
        return checkIn;
    }
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract=new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        String contractNumber = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);//合同编号
        contract.setElderId(Integer.valueOf(elder.getId()+""));
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);//开始时间
        contract.setEndDate(endDate);//结束时间
        boolean flag = startDate.isBefore(LocalDateTime.now());//判断开始时间是否在当前时间之前
        contract.setStatus((long) (flag?1:0));//合同的状态，0:未生效, 1: 已生效, 2: 已过期, 3: 已失效

        //直接执行新增的sql
        contractMapper.insert(contract);
    }
    private Elder insertOrUpdate(Bed bed, CheckInElderDto dto) {
        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtils.copyProperties(dto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, dto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb =  elderMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        }else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}

